<?php

namespace App\Http\Controllers\Backend\UserManage;

use App\Http\Controllers\Controller;
use App\Http\Repositories\UserManage\UserRepo;
use App\Http\Requests\Validators\Backend\UserManage\UserValidator;
use App\Traits\HelpFunctions;
use Illuminate\Http\Request;

/**
 * 用户相关
 */
class UserController extends Controller
{
    use HelpFunctions;

    const VALIDATOR = UserValidator::class;

    public function __construct()
    {
        $this->self_repo = new UserRepo;
    }

    public function search(Request $request)
    {
        //参数验证
        $args = $request->only(
            'name',
            'nickname',
            'gender',
            'phone',
            'card_id',
            'role_ids',
            'begin_time',
            'end_time',
        );

        $this->my_validate($args, 'searchRules');

        return $this->self_repo->search($args);
    }

    public function store(Request $request)
    {
        //参数验证
        $args = $request->only(
            'name',
            'gender',
            'phone',
            'card_id',
            'password',
        );

        $this->my_validate($args, 'storeRules');

        //添加数据
        return $this->returnResponse($this->self_repo->createOne($args));
    }

    public function delete($id)
    {
        return $this->self_repo->deleteById($id);
    }

    public function edit(Request $request, $id)
    {
        //参数验证
        $args = $request->only(
            'name',
            'gender',
            'phone',
            'card_id',
            'password',
        );
        $this->my_validate($args, 'editRules');
        if ($this->self_repo->uniqueExist($request->only('phone'),$id)) $this->clientError('该手机号已经存在');

        //根据id修改数据
        return $this->returnResponse($this->self_repo->editById($id, $args));
    }
}
